package com.youi.web;

import com.alibaba.fastjson.JSONObject;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Orderaftersale;
import com.youi.entity.Refundorder;
import com.youi.entity.User;
import com.youi.entity.Useraddress;
import com.youi.entity.Userorder;
import com.youi.entity.Userwechat;
import com.youi.entity.Yibaodivide;
import com.youi.entity.Yibaopayment;
import com.youi.entity.Yibaorefund;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.OrderaftersaleService;
import com.youi.service.RefundorderService;
import com.youi.service.UseraddressService;
import com.youi.service.UserorderService;
import com.youi.service.UserwechatService;
import com.youi.service.YibaodivideService;
import com.youi.service.YibaopaymentService;
import com.youi.service.YibaorefundService;
import com.youi.service.impl.TransactionalUserorderService;
import com.youi.third.kuaidi100.ExpressResult;
import com.youi.third.kuaidi100.ExpressUtil;
import com.youi.third.yibaopay.YibaopayUtil;
import com.youi.third.yibaopay.model.Divideresult;
import com.youi.third.yibaopay.model.Refundresult;
import com.youi.util.CommonInfoUtil;
import com.youi.util.JsonUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Userorder控制层
 *
 * @author Administrator
 */
@Controller
public class UserorderController extends HttpRequestManage implements ApplicationContextAware {

    @Autowired
    private UserorderService userorderService;
    @Autowired
    private UserwechatService userwechatService;
    @Autowired
    private UseraddressService useraddressService;
    @Autowired
    private OrderaftersaleService orderaftersaleService;
    @Autowired
    private YibaopaymentService yibaopaymentService;
    @Autowired
    private YibaorefundService yibaorefundService;
    @Autowired
    private RefundorderService refundorderService;
    @Autowired
    private YibaodivideService yibaodivideService;

    @Autowired
    private TransactionalUserorderService transactionalUserorderService;

    /**
     * M-11
     * 用户提交订单
     */
    @ResponseBody
    @RequestMapping("userGetInfo/submitUserorder")
    public String submitUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Integer orderType = getInteger("orderType", request);//订单类型(0直接下单 1拼团下单)
        Integer submitType = getInteger("submitType", request);//提交类型(0非购物车提交 1购物车提交)
        Long useraddressId = getLong("useraddressId", request);//用户地址id
        Long leaderId = optLong("leaderId", request);//团长id
        Long goodssizeId = optLong("goodssizeId", request);//商品规格id(非购物车提交时传入)
        Integer count = optInteger("count", request);//商品数量(非购物车提交时传入)
        String goodsandgoodscarIds = optString("goodsandgoodscarIds", request);//购物车与商品中间表id
        String remark = optString("remark", request);

        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.ID, useraddressId);
        Useraddress useraddress = useraddressService.getByParam(prams);
        if (useraddress == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "用户地址为空");
        }

        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, user.getId());
        Userwechat userwechat = userwechatService.getByParam(prams);
        if (userwechat == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "用户微信信息不存在");
        }

        String serialNumber = null;
        if (submitType == 0) {
            //非购物车提交
            serialNumber = transactionalUserorderService.submitUserOrder(
                    goodssizeId, count, null, user, userwechat, useraddress, leaderId, orderType, remark
            );
        } else if (submitType == 1) {
            //购物车提交
            serialNumber = transactionalUserorderService.submitUserOrder(
                    null, null, goodsandgoodscarIds, user, userwechat, useraddress, leaderId, orderType, remark
            );
        }

        if (serialNumber.contains("{")) {
            JSONObject data = JSONObject.parseObject(serialNumber);
            modelMap.put(CommonInfoUtil.JSONCODE, data.getString("code"));
            modelMap.put(CommonInfoUtil.JSONMSG, data.getString("msg"));
            return JsonUtil.toJson(modelMap);
        }
        modelMap.put("orderId", serialNumber);
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作完成");
        return JsonUtil.toJson(modelMap);
    }


    /**
     * 批量删除Userorder
     */
    @ResponseBody
    @RequestMapping("delUserorderByIds")
    public String delUserorderByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        String ids = getString("ids", request);
        List<Long> idsList = ObjectUtil.getIdListByIds(ids);
        if (idsList == null || idsList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.ID, idsList);
        List<Userorder> userorderList = userorderService.getByParams(params);
        if (userorderList == null || userorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        for (Userorder userorder : userorderList) {
            userorder.setDelStatus(DelStatus.DEL);
        }
        userorderService.saveOrUpdateAll(userorderList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * M-14
     * 查询用户订单列表
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/getUserorder")
    public String getUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException, IOException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        String status = optString("status", request);
        Integer refund = optInteger("refund", request);
        String des = optString("des", request, Common.DESC);
        String pms = optString("pms", request);
        Date start = optDate("start", request, "yyyy-MM-dd HH:mm:ss");
        Date end = optDate("end", request, "yyyy-MM-dd HH:mm:ss");
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, user.getId());
        //状态(-1已关闭 0待付款 1待发货 2待收货 3待评价 4已完成 5售后 )
        if (status != null) {
            List<Integer> integerList = ObjectUtil.getIntListByIds(status);
            if (integerList != null && integerList.size() > 0) {
                prams.put(Common.STATUS, integerList);
            }
        }
        //退款(0否 1是)
        if (refund != null) {
            prams.put("refund", refund);
        }
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, des);
        Map<String, Object> searchPram = null;
        if (pms != null) {
            searchPram = new HashMap<String, Object>();
        }
        Map<String, Object> startTime = null;
        if (start != null) {
            startTime = new HashMap<String, Object>();
            startTime.put(Common.GMTCREATED, start);
        }
        Map<String, Object> endTime = null;
        if (end != null) {
            endTime = new HashMap<String, Object>();
            endTime.put(Common.GMTCREATED, end);
        }
        List<Userorder> userorderList = userorderService.getByParamsList(prams, searchPram, sortPram, (pageIndex - 1) * pageNum, pageNum, startTime, endTime);
        if (userorderList == null || userorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        Integer pageCount = userorderService.getCountByParamss(prams, searchPram, startTime, endTime);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);            //pageIndex     查询页数
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, userorderList);        //jsonObjectList json对象集合
        userorderService.getUserorderMsg(userorderList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * M-15
     * 查询用户订单详情
     */
    @ResponseBody
    @RequestMapping("userGetInfo/getUserorderById")
    public String getUserorderById(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorderService.getUserorderMsg(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", userorder);//jsonObject	json对象
    }

//	@ResponseBody
//	@RequestMapping("testGetUserorderIds")
//	public String testGetUserorderIds(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
//			String serialNumber = getString("serialNumber",request);
//			HashMap<String,Object> params = new HashMap<>();
//			params.put("serialNumber",serialNumber);
//			Yibaopayment payment = yibaopaymentService.getByParam(params, null, null);
//			String orderNos = payment.getOrderNos();
//			List<String> idsList= ObjectUtil.getStrListByIds(orderNos);
//			params = new HashMap<>();
//			params.put("orderNo",idsList);
//			List<Userorder> orders = userorderService.getByParams(params);
//			String orderIds = "";
//			for (Userorder order : orders){
//				if (orderIds.length() >0){
//					orderIds += ",";
//				}
//				orderIds += order.getId();
//			}
//		return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",orderIds);//jsonObject	json对象
//	}


    /**
     * M-35
     * 取消订单
     */
    @ResponseBody
    @RequestMapping("userGetInfo/cancelUserorder")
    public String cancelUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
//			synchronized (lock) {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        transactionalUserorderService.cancelUserOrder(userorder, false);
//				userorderService.getUserorderMsg(userorder);
//				userorder.setStatus(-1);
//				userorder.setGmtClose(new Date());
//				for (Ordergoods ordergoods : userorder.getOrdergoodsList()) {
//					Goods goods=goodsService.get(ordergoods.getGoodsId());
//					goodsService.getGoodsMsg(goods, null);
//					if (goods!=null) {
//						Map<String, Object> prams=new HashMap<String, Object>();
//						prams.put(Common.DELSTATUS, DelStatus.NODEL);
//						prams.put("goodsId", goods.getId());
//						prams.put("specification", ordergoods.getSpecification());
//						prams.put("price", ordergoods.getSlaePrice());
//						Goodssize goodssize=goodssizeService.getByParam(prams);
//						if (goodssize!=null) {
//							Goodssize redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//							if (redisGoodssize==null) {
//								goodssize.setAllStockNum(goods.getAllStockNum());
//								goodssize.setRealStockCnt(goods.getRealStockCnt());
//								goodssize.setRealSaleCnt(goods.getRealSaleCnt());
//								JedisUtils.setObject(goodssize.getId().toString(), goodssize);
//								redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//							}
//
//							if (redisGoodssize.getRealStockNum()!=null) {
//								redisGoodssize.setRealStockNum(redisGoodssize.getRealStockNum()+ordergoods.getCount());
//							}
//							if (redisGoodssize.getSaleNum()!=null) {
//								redisGoodssize.setSaleNum(redisGoodssize.getSaleNum()-ordergoods.getCount());
//							}
//							redisGoodssize.setRealSaleCnt(redisGoodssize.getRealSaleCnt()-ordergoods.getCount());
//							if (redisGoodssize.getRealSaleCnt()<=0) {
//								goods.setRealSaleCnt(0);
//							}
////							if (goods.getRealSaleCnt()>0) {
////								goods.setRealSaleCnt(goods.getRealSaleCnt()-ordergoods.getCount());
////							}
//							if (redisGoodssize.getAllStockNum()>=0) {
//								goods.setStatus(1);
//							}
//							goods.setRealSaleCnt(redisGoodssize.getRealSaleCnt());
//							goodssizeService.saveOrUpdate(redisGoodssize);
//							goodsService.saveOrUpdate(goods);
//							JedisUtils.setObject(goodssize.getId().toString(), redisGoodssize);
//						}
//					}
//				}
//				userorderService.saveOrUpdate(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
//			}
    }

    /**
     * M-42
     * 申请订单售后
     */
    @ResponseBody
    @RequestMapping("userGetInfo/afterSaleUserorder")
    public String afterSaleUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long orderId = getLong("orderId", request);
        Integer isTake = getInteger("isTake", request);
        String reason = getString("reason", request);
        String explain = optString("explain", request);
        String imgs = optString("imgs", request);
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Userorder userorder = userorderService.get(orderId);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        if (userorder.getIsAfterSale() == 1) {
            return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "该订单已经过了售后时间，暂不支持线上退款，请联系客服。");
        }
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", userorder.getOrderNo());
        Refundorder refundorder = refundorderService.getByParam(prams);
        if (refundorder != null) {
            return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "请勿重复提交");
        }
        userorder.setStatus(5);
        userorder.setRefund(0);
        userorderService.saveOrUpdate(userorder);
        String refundOrderNo = "3" + new Date().getTime() + user.getId().toString();
        orderaftersaleService.saveOrUpdate(new Orderaftersale(user.getId(), orderId, isTake, reason, explain, imgs));
        refundorder = new Refundorder(user.getId(), userorder.getMerchantId(), refundOrderNo, userorder.getOrderNo(),
                userorder.getMerchantName(), userorder.getMerchantCode(), user.getPhone(), userorder.getPayableAmount());
        refundorder.setOrderType(1);
        refundorderService.saveOrUpdate(refundorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * 订单直接退款
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/directRefundUserorder")
    public String directRefundUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
//			synchronized (lock) {
        String orderNo = getString("orderNo", request);
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("orderNos", orderNo);
        Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams, searchParams, null);
        if (yibaopayment == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单流水信息不存在");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", orderNo);
        Userorder userorder = userorderService.getByParam(prams);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单不存在");
        }
        if (userorder.getStatus() >= 2) {
            return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "订单已发货无法退款");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", orderNo);
        Yibaodivide yibaodivide = yibaodivideService.getByParam(prams);
        if (yibaodivide == null) {
            Divideresult divideresult = YibaopayUtil.yibaoDivide(yibaopayment, userorder);
            if (divideresult != null && divideresult.getCode().equals("OPR00000")) {
                yibaodivide = new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), orderNo, divideresult.getUniqueOrderNo(),
                        divideresult.getDivideRequestId(), divideresult.getDivideDetail());
                yibaodivideService.saveOrUpdate(yibaodivide);
            } else {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, divideresult.getMessage(), divideresult);
            }
        } else {
            JSONObject jsonObject = YibaopayUtil.getYibaoDivide(yibaodivide.getOrderId(), yibaodivide.getUniqueOrderNo(), yibaodivide.getDivideRequestId());
            if (jsonObject != null && !jsonObject.getString("code").equals("OPR00000")) {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, jsonObject.getString("message"), jsonObject);
            }
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", orderNo);
        Yibaorefund yibaorefund = yibaorefundService.getByParam(prams);
        if (yibaorefund == null) {
            Refundresult refundresult = YibaopayUtil.yibaoRefund(yibaodivide, userorder, yibaopayment);
            if (refundresult != null && refundresult.getCode().equals("OPR00000")) {
                String refundOrderNo = "3" + new Date().getTime() + user.getId().toString();
                refundorderService.saveOrUpdate(new Refundorder(user, 0, refundOrderNo, userorder));
                yibaorefund = new Yibaorefund(refundresult, yibaopayment, userorder.getOrderNo());
                yibaorefundService.saveOrUpdate(yibaorefund);
            } else {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, refundresult.getMessage(), refundresult);
            }
        } else {
            JSONObject data = YibaopayUtil.yibaoGetRefund(yibaorefund.getOrderId(), yibaorefund.getUniqueRefundNo(), yibaorefund.getRefundOrderNo());
            if (data != null && !data.getString("code").equals("OPR00000")) {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, data.getString("message"), data);
            }
        }
        transactionalUserorderService.cancelUserOrder(userorder, true);
//				prams=new HashMap<String, Object>();
//				prams.put(Common.DELSTATUS, DelStatus.NODEL);
//				prams.put("orderId", userorder.getId());
//				List<Ordergoods> ordergoodsList=ordergoodsService.getByParams(prams);
//				if (ordergoodsList!=null&&ordergoodsList.size()>0) {
//					for (Ordergoods ordergoods : ordergoodsList) {
//						prams=new HashMap<String, Object>();
//						prams.put(Common.DELSTATUS, DelStatus.NODEL);
//						prams.put("goodsId", ordergoods.getGoodsId());
//						prams.put("specification", ordergoods.getSpecification());
//						prams.put("price", ordergoods.getSlaePrice());
//						Goodssize goodssize=goodssizeService.getByParam(prams);
//						if (goodssize!=null) {
//							Goods goods=goodsService.get(goodssize.getGoodsId());
//							goodsService.getGoodsMsg(goods, user);
//							if (goods!=null) {
//								Goodssize redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//								if (redisGoodssize==null) {
//									goodssize.setAllStockNum(goods.getAllStockNum());
//									goodssize.setRealStockCnt(goods.getRealStockCnt());
//									goodssize.setRealSaleCnt(goods.getRealSaleCnt());
//									JedisUtils.setObject(goodssize.getId().toString(), goodssize);
//									redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//								}
//								redisGoodssize.setRealStockNum(redisGoodssize.getRealStockNum()+ordergoods.getCount());
//								redisGoodssize.setSaleNum(redisGoodssize.getSaleNum()-ordergoods.getCount());
//								redisGoodssize.setRealSaleCnt(redisGoodssize.getRealSaleCnt()-ordergoods.getCount());
//								if (redisGoodssize.getRealSaleCnt()<=0) {
//									goods.setRealSaleCnt(0);
//								}
////								if (goods.getRealSaleCnt()>0) {
////									goods.setRealSaleCnt(goods.getRealSaleCnt()-ordergoods.getCount());
////								}
//								if (redisGoodssize.getRealSaleCnt()<=redisGoodssize.getAllStockNum()) {
//									goods.setStatus(1);
//								}
//								goods.setRealSaleCnt(redisGoodssize.getRealSaleCnt());
//								goodsService.saveOrUpdate(goods);
//								goodssizeService.saveOrUpdate(redisGoodssize);
//								JedisUtils.setObject(goodssize.getId().toString(), redisGoodssize);
//							}
//						}
//					}
//					userorder.setStatus(-1);
//					userorder.setRefund(1);
//					userorder.setGmtClose(new Date());
//					userorderService.saveOrUpdate(userorder);
//				}
        modelMap.put("orderNo", userorder.getOrderNo());
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
//			}
    }

    /**
     * M-37
     * 查询订单物流信息
     */
    @ResponseBody
    @RequestMapping("userGetInfo/getUserorderExpressMsg")
    public String getUserorderExpressMsg(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        String result = ExpressUtil.getExpressMsg(ObjectUtil.removeAllBlank(userorder.getExpressCode()), ObjectUtil.removeAllBlank(userorder.getExpressNo()), ObjectUtil.removeAllBlank(userorder.getPhone()), null, null, 0);
        ExpressResult expressResult = JsonUtil.fromJson(result, ExpressResult.class);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", expressResult);//jsonObject	json对象
    }

    /**
     * M-38
     * 修改订单为已收货
     */
    @ResponseBody
    @RequestMapping("userGetInfo/editUserorderByTake")
    public String editUserorderByTake(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorder.setStatus(3);
        userorder.setGmtReceiving(new Date());
        userorder.setGmtComplete(userorder.getGmtReceiving());
        userorderService.saveOrUpdate(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", userorder);//jsonObject	json对象
    }


    /**
     * 查询所有Userorder
     *
     * @param modelMap
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("getAllUserorder")
    public String getAllUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        List<Userorder> userorderList = userorderService.getByParams(null);
        if (userorderList == null || userorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", userorderList);//jsonObjectList	json对象集合
    }

//		/**
//		 * 提交单个商品逻辑
//		 * @param goodssizeId 规格id
//		 * @param count 购买数量
//		 * @param user 用户信息
//		 * @param userorder	订单信息
//		 * @param userwechat 微信信息
//		 * @param useraddress 地址信息
//		 * @param leaderId 团长id
//		 * @param orderType 订单类型
//		 * @return
//		 */
//		private String sumbitSingleGoods(Long goodssizeId,Integer count,User user,Userorder userorder,Userwechat userwechat,Useraddress useraddress,Long leaderId,Integer orderType,String remark) {
//			Map<String, Object> prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put(Common.ID, goodssizeId);
//			Goodssize goodssize=goodssizeService.getByParam(prams);
//			if (goodssize==null) {
//				return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "商品规格不存在");
//			}
//			prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put(Common.ID, goodssize.getGoodsId());
//			Goods goods=goodsService.getByParam(prams);
//			if (goods==null) {
//				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "商品不存在");
//			}
//			if (goods.getStatus()!=1) {
//				return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "商品非出售状态无法提交出售");
//			}
//			goodsService.getGoodsMsg(goods, user);
//			Goodssize redisGoodssize=JedisUtils.getObject(goodssizeId.toString(), Goodssize.class);
//			if (redisGoodssize==null) {
//				goodssize.setAllStockNum(goods.getAllStockNum());
//				goodssize.setRealStockCnt(goods.getRealStockCnt());
//				goodssize.setRealSaleCnt(goods.getRealSaleCnt());
//				JedisUtils.setObject(goodssizeId.toString(), goodssize);
//				redisGoodssize=JedisUtils.getObject(goodssizeId.toString(), Goodssize.class);
//			}
//			if (redisGoodssize.getAllStockNum()==null) {
//				redisGoodssize.setAllStockNum(goods.getAllStockNum());
//			}
//			if (redisGoodssize.getRealStockCnt()==null) {
//				goodssize.setRealStockCnt(goods.getRealStockCnt());
//			}
//			if (redisGoodssize.getRealSaleCnt()==null) {
//				redisGoodssize.setRealSaleCnt(goods.getRealSaleCnt());
//			}
//			if (redisGoodssize.getAllStockNum()<=0) {
//				goods.setStatus(2);
//				goodsService.saveOrUpdate(goods);
//				JedisUtils.del(goodssizeId.toString());
//				return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "商品已售罄无法下单");
//			}
//			if (count>redisGoodssize.getRealStockNum()) {
//				JedisUtils.del(goodssizeId.toString());
//				return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "商品库存不足");
//			}
//			prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put("goodsId", goods.getId());
//			prams.put(Common.TYPE, 1);
//			Goodsimgs goodsimgs=goodsimgsService.getByParam(prams);
//			if (goodsimgs==null&&goodsimgs.getImgs().length()>0) {
//				return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "商品图片为空");
//			}
//			prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put(Common.ID, goods.getMerchantId());
//			Merchant merchant=merchantService.getByParam(prams);
//			if (merchant==null) {
//				return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "商家信息不存在");
//			}
//			userorder=userorderService.addUserorder(user, useraddress, merchant, orderType);
//			userorder.setUnioid(userwechat.getUnionid());
//			userorder.setAmount(count*goodssize.getPrice());
//			userorder.setPayableAmount(count*goodssize.getPrice());
//			if (leaderId!=null) {
//				userorder.setLeaderId(leaderId);
//			}else {
//				userorder.setLeaderId(0L);
//			}
//			if (remark!=null&&remark.length()>0) {
//				userorder.setRemark(remark);
//			}
//			userorderService.saveOrUpdate(userorder);
//			Ordergoods ordergoods=new Ordergoods(userorder.getId(), merchant.getId(), goods, goodsimgs.getImgs(), redisGoodssize, count, count*redisGoodssize.getPrice());
//			ordergoodsService.saveOrUpdate(ordergoods);
//			if (redisGoodssize.getRealStockNum()!=null) {
//				redisGoodssize.setRealStockNum(redisGoodssize.getRealStockNum()-count);
//			}
//			if (redisGoodssize.getSaleNum()!=null) {
//				redisGoodssize.setSaleNum(redisGoodssize.getSaleNum()+count);
//			}
//			goodssizeService.saveOrUpdate(redisGoodssize);
//			redisGoodssize.setRealSaleCnt(redisGoodssize.getRealSaleCnt()+count);
//			goods.setRealSaleCnt(redisGoodssize.getRealSaleCnt());
//			goodsService.saveOrUpdate(goods);
//			JedisUtils.setObject(goodssizeId.toString(), redisGoodssize);
//			String serialNumber=ObjectUtil.getOrderNo(0, user.getId().toString());
//			Yibaopayment yibaopayment=new Yibaopayment(user.getId(), serialNumber, userorder.getPayableAmount());
//			yibaopayment.setOrderNos(userorder.getOrderNo());
//			yibaopaymentService.saveOrUpdate(yibaopayment);
//			return yibaopayment.getSerialNumber();
//		}
//
//		/**
//		 * 提交购物车商品逻辑
//		 * @param user
//		 * @param goodsandgoodscarIds
//		 * @param userorder
//		 * @param useraddress
//		 * @param leaderId
//		 * @param orderType
//		 * @param remark
//		 * @return
//		 */
//		private String sumbitGoodscarGoods(User user,String goodsandgoodscarIds,Userorder userorder,Useraddress useraddress,Long leaderId,Integer orderType,String remark) {
//			List<String> orderNoList=new ArrayList<String>();
//			Map<String, Object> prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put(Common.USERID, user.getId());
//			Goodscar goodscar=goodscarService.getByParam(prams);
//			Double payAllAmount=0.00;
//			if (goodscar!=null) {
//				List<Long> merchantIds=new ArrayList<Long>();
//				List<Long> idsList=ObjectUtil.getIdListByIds(goodsandgoodscarIds);
//				Map<String, Object> params=new HashMap<String, Object>();
//				if (idsList==null||idsList.size()==0) {
//					return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "购物车商品信息id错误");
//				}
//				params.put(Common.DELSTATUS, DelStatus.NODEL);
//				params.put(Common.ID, idsList);
//				List<Goodsandgoodscar> goodsandgoodscarList=goodsandgoodscarService.getByParams(params);
//				if (goodsandgoodscarList==null||goodsandgoodscarList.size()==0) {
//					return null;
//				}
//				for (Goodsandgoodscar goodsandgoodscar : goodsandgoodscarList) {
//					params=new HashMap<String, Object>();
//					params.put(Common.DELSTATUS, DelStatus.NODEL);
//					params.put(Common.ID, goodsandgoodscar.getGoodsId());
//					Goods goods=goodsService.getByParam(params);
//					if (goods!=null) {
//						merchantIds.add(goods.getMerchantId());
//					}
//				}
//				merchantIds=ObjectUtil.removeDuplicate(merchantIds);
//				for (Long merchantId : merchantIds) {
//					Double amount=0.00;
//					Double payableAmount=0.00;
//					params=new HashMap<String, Object>();
//					params.put(Common.DELSTATUS, DelStatus.NODEL);
//					params.put(Common.ID, merchantId);
//					Merchant merchant=merchantService.getByParam(params);
//					if (merchant==null) {
//						return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "商家信息不存在");
//					}
//					userorder=userorderService.addUserorder(user, useraddress, merchant, orderType);
//					if (leaderId!=null) {
//						userorder.setLeaderId(leaderId);
//					}else {
//						userorder.setLeaderId(0L);
//					}
//					userorder.setAmount(0.00);
//					userorder.setPayableAmount(0.00);
//					Double goodsAnt=0.00;
//					for (Goodsandgoodscar goodsandgoodscar : goodsandgoodscarList) {
//						params=new HashMap<String, Object>();
//						params.put(Common.DELSTATUS, DelStatus.NODEL);
//						params.put(Common.ID, goodsandgoodscar.getGoodsId());
//						Goods goods=goodsService.getByParam(params);
//						if (goods==null) {
//							return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "商品信息不存在");
//						}
//						if (goods.getStatus()!=1) {
//							return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "商品非出售状态无法出售");
//						}
//						goodsService.getGoodsMsg(goods, user);
//						if (goods.getMerchantId()==merchantId) {
//							prams=new HashMap<String, Object>();
//							prams.put(Common.ID, goodsandgoodscar.getGoodssizeId());
//							Goodssize goodssize=goodssizeService.getByParam(prams);
//							if (goodssize==null) {
//								return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "商品规格不存在");
//							}
//							Goodssize redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//							if (redisGoodssize==null) {
//								goodssize.setAllStockNum(goods.getAllStockNum());
//								goodssize.setRealStockCnt(goods.getRealStockCnt());
//								goodssize.setRealSaleCnt(goods.getRealSaleCnt());
//								JedisUtils.setObject(goodssize.getId().toString(), goodssize);
//								redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//							}
//							if (redisGoodssize.getAllStockNum()==null) {
//								redisGoodssize.setAllStockNum(goods.getAllStockNum());
//							}
//							if (redisGoodssize.getRealStockCnt()==null) {
//								goodssize.setRealStockCnt(goods.getRealStockCnt());
//							}
//							if (redisGoodssize.getRealSaleCnt()==null) {
//								redisGoodssize.setRealSaleCnt(goods.getRealSaleCnt());
//							}
//							if (redisGoodssize.getAllStockNum()<=0) {
//								goods.setStatus(2);
//								goodsService.saveOrUpdate(goods);
//								JedisUtils.del(goodssize.getId().toString());
//								return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "商品已售罄无法下单");
//							}
//							if (goodsandgoodscar.getCount()>redisGoodssize.getRealStockNum()) {
//								JedisUtils.del(goodssize.getId().toString());
//								return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "商品库存不足");
//							}
//							prams=new HashMap<String, Object>();
//							prams.put(Common.DELSTATUS, DelStatus.NODEL);
//							prams.put("goodsId", goods.getId());
//							prams.put(Common.TYPE, 1);
//							Goodsimgs goodsimgs=goodsimgsService.getByParam(prams);
//							if (goodsimgs==null&&goodsimgs.getImgs().length()>0) {
//								return null;
//							}
//							userorderService.saveOrUpdate(userorder);
//							Ordergoods ordergoods=new Ordergoods(userorder.getId(), merchant.getId(), goods, goodsimgs.getImgs(), goodssize, goodsandgoodscar.getCount(), goodsandgoodscar.getAmount());
//							ordergoodsService.saveOrUpdate(ordergoods);
//							goodsandgoodscar.setDelStatus(DelStatus.DEL);
//							goodscar.setAmount(goodscar.getAmount()-goodsandgoodscar.getAmount());
//							goodsandgoodscarService.saveOrUpdate(goodsandgoodscar);
//							redisGoodssize.setRealStockNum(redisGoodssize.getRealStockNum()-goodsandgoodscar.getCount());
//							redisGoodssize.setSaleNum(redisGoodssize.getSaleNum()+goodsandgoodscar.getCount());
//							redisGoodssize.setRealSaleCnt(redisGoodssize.getRealSaleCnt()+goodsandgoodscar.getCount());
//							goods.setRealSaleCnt(redisGoodssize.getRealSaleCnt());
//							goodssizeService.saveOrUpdate(redisGoodssize);
//							JedisUtils.setObject(goodssize.getId().toString(), redisGoodssize);
//							goodsService.saveOrUpdate(goods);
//							goodscarService.saveOrUpdate(goodscar);
//							goodsAnt+=ordergoods.getAmount();
//						}
//					}
//					amount+=goodsAnt;
//					payableAmount+=goodsAnt;
//					orderNoList.add(userorder.getOrderNo());
//					userorder.setAmount(amount);
//					userorder.setPayableAmount(payableAmount);
//					if (remark!=null&&remark.length()>0) {
//						userorder.setRemark(remark);
//					}
//					userorderService.saveOrUpdate(userorder);
//					payAllAmount+=amount;
//				}
//			}
//			String orderNos=ObjectUtil.listToString(orderNoList);
//			String serialNumber=ObjectUtil.getOrderNo(0, user.getId().toString());
//			Yibaopayment yibaopayment=new Yibaopayment(user.getId(), serialNumber,payAllAmount);
//			yibaopayment.setOrderNos(orderNos);
//			yibaopaymentService.saveOrUpdate(yibaopayment);
//			return yibaopayment.getSerialNumber();
//		}

    //		/**定时器线程池*/
//		private static ScheduledThreadPoolExecutor executor;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//			// TODO Auto-generated method stub
//			if (lock==null) {
//				lock = new byte[0];
//				executor=new ScheduledThreadPoolExecutor(1);
//			}
    }
}
